package com.scaffold.authority.service;

import java.sql.Timestamp;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wangjg.commons.page.Page;

import com.scaffold.authority.dao.AuthorityDAO;
import com.scaffold.authority.dao.RoleAuthorityRelationDAO;
import com.scaffold.authority.dao.RoleDAO;
import com.scaffold.authority.entity.Authority;
import com.scaffold.authority.entity.Role;
import com.scaffold.authority.entity.RoleAuthorityRelation;


@Service
@Transactional
public class RoleService{

	@Autowired
	private RoleDAO roleDAO;
	@Autowired
	private RoleAuthorityRelationDAO roleAuthorityRelationDAO;
	@Autowired
	private AuthorityDAO authorityDAO;

	public Role getRole(Long id ) {
		return this.roleDAO.findById(id);
	}

	public void save(Role role){
		Timestamp now = new Timestamp(System.currentTimeMillis());
		if(role.getId()==null){
			role.setCreated(now);
			role.setModified(now);
			this.roleDAO.save(role);
		}else{
			role.setModified(now);
			this.roleDAO.update(role);
		}
	}

	public void update(Role role){
		Timestamp now = new Timestamp(System.currentTimeMillis());
		role.setModified(now);
		this.roleDAO.update(role);
	}

	public void delete(Role role){
		this.roleAuthorityRelationDAO.deleteByProperty("roleId", role.getId());
		this.roleDAO.delete(role);
	}

	public void batchDelete(String idseq) {
		String[] sa = idseq.split(",");
		for(String s:sa){
			Long id = Long.parseLong(s);
			this.roleAuthorityRelationDAO.deleteByProperty("roleId", id);
			this.roleDAO.delete(id);
		}
	}

	public List<Role> pageQuery(Page page , Integer type, String name, String intro, String keyword) {
		return this.roleDAO.pageQuery(page , type, name, intro, keyword);
	}


	public void saveAuthoritys(Long roleId, String authorityIds) {
		roleAuthorityRelationDAO.deleteByProperty("roleId", roleId);
		
		if(roleId==null || authorityIds==null || authorityIds.isEmpty()){
			return;
		}
		String[] idseq = authorityIds.split(",");
		Timestamp now = new Timestamp(System.currentTimeMillis());
		for(String s:idseq){
			Long authorityId = Long.parseLong(s);
			RoleAuthorityRelation item = new RoleAuthorityRelation();
			item.setRoleId(roleId);
			item.setAuthorityId(authorityId);
			item.setCreated(now);
			item.setModified(now);
			roleAuthorityRelationDAO.save(item);
		}
	}

	public List<Long> getAuthorityIdList(Long roleId) {
		return roleAuthorityRelationDAO.findPropertyList("authorityId", "roleId", roleId);
	}

	public List<Authority> getAuthorityList(Long roleId) {
		List<Long> idList =  roleAuthorityRelationDAO.findPropertyList("authorityId", "roleId", roleId);
		return authorityDAO.findByIdList(idList);
	}

}
